import React, { useEffect, useState } from 'react';
//引入scss
import '../../../scss/zw/StaffManage.scss'
//插件
import { Breadcrumb, Divider, Form, Button, Input, Select, Table, Modal, message } from 'antd';
//图标
import {
    SearchOutlined, PlusCircleOutlined, DeleteOutlined, FormOutlined
} from '@ant-design/icons';

import axios from 'axios';

//请求
import { Staff_Search, Staff_list, Staff_add, Staff_sub, Staff_edit } from '../../../tools/api'

//引入自定义钩子函数
//员工状态
import { useStaffLeaveList } from "../../../hooks/zwHooks/index";
//员工职位
import { useStaffManageJob } from "../../../hooks/zwHooks/index";

function StaffManage(props) {
    //定义组件状态  
    //员工管理列表数据
    var [staffManageList, setStaffManageList] = useState([])
    //调用钩子函数，定义员工职位列表
    const [staffManageJob, setStaffManageJob] = useStaffManageJob()
    //调用钩子函数，获取员工状态列表
    const [staffLeaveList, setStaffLeaveList] = useStaffLeaveList()

    //新增表单框是否显示
    var [isModalOpen, setIsModalOpen] = useState(false);
    //编辑表单框是否显示
    var [isModalOpenEdit, setIsModalOpenEdit] = useState(false);
    //分页
    var [page, setPage] = useState(1);  ///页码
    var [total, setTotal] = useState(0);   //总数
    var [pageSize, setPageSize] = useState(10);   //每页的个数
    //表格是否有loading效果
    var [loading, setLoading] = useState(false);
    //定义表格选择行的key
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);


    //发请求获取员工列表的数据
    useEffect(() => {
        Staff_list().then((res) => {
            // console.log(res.data);
            setStaffManageList(res.data)
            setLoading(true)
            setTimeout(() => {
                setLoading(false)
            }, 500);
        })
    }, [])


    //当表格行的选择发生改变时执行
    const onSelectChange = (newSelectedRowKeys) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };


    //新增员工，表单验证通过，发起请求
    const onFinish = (values) => {
        console.log('Success:', values);
        // 发起添加请求
        Staff_add(values).then((res) => {
            if (res.status == 201) {
                message.open({ type: 'success', content: '新增成功!' });
                //关闭新增页
                setIsModalOpen(false);
                update()
                setLoading(true)
                setTimeout(() => {
                    setLoading(false)
                }, 500);
            } else {
                message.open({ type: 'error', content: '新增失败!' });
            }
        })
    };

    //新增弹框显示
    const shouModal = (values) => {
        setIsModalOpen(true);
    }
    //新增弹框的取消
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    //条件搜索
    const onSearch = (value) => {
        // console.log(value)
        Staff_Search({
            account_like: value.account,
            name_like: value.name,
            job_like: value.job,
            leave_like: value.leave
        }).then((res) => {
            setStaffManageList(res.data)
            setLoading(true)
            setTimeout(() => {
                setLoading(false)
            }, 500);
            // console.log(res.data)
        })
    }

    //删除
    var del = (record) => {
        console.log(record);
        Staff_sub(record.id).then((res) => {
            console.log(res)
            message.open({ type: 'success', content: '删除成功!' });
            // setPageSize(pageSize)
        })
        update()
        setLoading(true)
        setTimeout(() => {
            setLoading(false)
        }, 500);
    }

    //让列表数据更新的函数
    const update = () => {
        Staff_list().then((res) => {
            // console.log(res.data);
            setStaffManageList(res.data)
        })
    }

    //编辑
    var { useForm } = Form  //解构useForm
    var [form] = useForm()   //获取form实例,然后需要在表单里面绑定form
    var [customerid, setCustomerid] = useState([])

    const edit = (record) => {
        // console.log(record);
        //深拷贝原有的数据，防止原有的数据被改动
        // record = JSON.parse(JSON.stringify(record))
        //显示编辑对话框
        editshouModal()
        //一次性设置多个value进行更改
        form.setFieldsValue(record)
        // id = record.id
        setCustomerid(record.id)

    }
    const onFinishEdit = (values) => {
        console.log(values);
        axios.patch(`http://localhost:4000/StaffManagetable/${customerid}`,
            {
                userid: values.userid,
                name: values.name,
                account: values.account,
                department: values.department,
                job: values.job,
                phone: values.phone,
                leave: values.leave,
                time: values.time
            }).then((res) => {
                edithandleCancel();//弹框消失
                message.open({ type: 'success', content: '修改成功!' });
                update()
                setLoading(true)
                setTimeout(() => {
                    setLoading(false)
                }, 500);

            })
    }
    //编辑弹框显示
    const editshouModal = (values) => {
        setIsModalOpenEdit(true);
    }
    //编辑弹框的取消
    const edithandleCancel = () => {
        setIsModalOpenEdit(false);
    };

    //定义表格的表头
    const columns = [
        {
            title: '员工编号',   //表格列的名字（显示在表头上）
            dataIndex: 'userid',  //数据对应的属性名
            key: 'userid',
        },
        {
            title: '员工姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '员工账户',
            dataIndex: 'account',
            key: 'account',
        },
        {
            title: '所在部门',
            key: 'department',
            dataIndex: 'department',
        },
        {
            title: '员工职位',
            key: 'job',
            dataIndex: 'job',
        },
        {
            title: '手机号',
            key: 'phone',
            dataIndex: "phone",
        },
        {
            title: '员工状态',
            key: 'leave',
            dataIndex: 'leave',
        },
        {
            title: '添加时间',
            key: 'time',
            dataIndex: "time",
        },
        {
            title: '操作',
            key: 'action',
            dataIndex: 'action',
            render: (_, record) => (
                <>
                    <i className='remove' onClick={() => { edit(record) }}>
                        <FormOutlined />
                    </i>
                    <i className="delete" onClick={() => { del(record) }}><DeleteOutlined /></i>
                </>
            ),
        },
    ]
    return (
        <div className="staffManage">
            <div className="staffManageHeader">
                <Breadcrumb>
                    <Breadcrumb.Item>权限管理</Breadcrumb.Item>
                    <Breadcrumb.Item>
                        <a>员工管理</a>
                    </Breadcrumb.Item>
                </Breadcrumb>
            </div>
            <Divider />
            {/* 搜索 */}
            <div className="staffManageSearch">
                <Form
                    onFinish={onSearch} className="search"
                >
                    <Form.Item
                        label="员工账号"
                        name="account"
                        rules={[{ message: '请输入员工账号' }]}
                    >
                        <Input placeholder="请输入员工账号" />
                    </Form.Item>
                    <Form.Item
                        label="员工姓名"
                        name="name"
                        rules={[{ message: '请输入员工姓名' }]}
                    >
                        <Input placeholder="请输入员工姓名" />
                    </Form.Item>
                    <Form.Item
                        label="员工职位"
                        name="job"
                        rules={[{ message: '选择职位' }]}
                    >
                        <Select
                            style={{ width: 120 }}
                            options={staffManageJob}
                        />
                    </Form.Item>
                    <Form.Item
                        label="员工状态"
                        name="leave"
                        rules={[{ message: '选择状态' }]}
                    >
                        <Select
                            style={{ width: 120 }}
                            options={staffLeaveList}
                        />
                    </Form.Item>
                    <Form.Item className="formItem" className="formItem">
                        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>搜索</Button>
                    </Form.Item>
                    <Form.Item className="formItem" className="formItem">
                        <Button type="primary" icon={<PlusCircleOutlined />} onClick={shouModal}>添加</Button>
                    </Form.Item>
                </Form>
                {/* <div classNam="staffManageButton">
                    <Button type="primary" icon={<PlusCircleOutlined />} onClick={shouModal}>添加</Button>
                </div> */}
            </div>
            {/* 数据列表 */}
            <div className="staffManageList">
                {/* pagination分页器，是一个对象   pagination={{ current, pageSize, total }} onChange={onChange} */}
                <Table
                    columns={columns}
                    dataSource={staffManageList}
                    loading={loading}
                    pagination={{ page, pageSize, total }}
                    rowSelection={rowSelection} />
            </div>
            {/* 新增的对话框 */}
            <div className="addStaff">
                <Modal title="新增" open={isModalOpen} footer={[]} className="modal"
                >
                    {/* footer={[]} 取消底部的两个按钮 */}
                    <Form
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        onFinish={onFinish}
                    >
                        <Form.Item
                            label="员工编号"
                            name="userid"
                            rules={[{ required: true, message: '输入员工编号' }]}
                        >
                            <Input placeholder='输入员工编号' />
                        </Form.Item>
                        <Form.Item
                            label="姓名"
                            name="name"
                            rules={[{ required: true, message: '输入姓名' }]}
                        >
                            <Input placeholder='输入姓名' />
                        </Form.Item>
                        <Form.Item
                            label="账号"
                            name="account"
                            rules={[{ required: true, message: '输入账号' }]}
                        >
                            <Input placeholder='输入账号' />
                        </Form.Item>
                        <Form.Item
                            label="所在部门"
                            name="department"
                            rules={[{ required: true, message: '输入所在部门' }]}
                        >
                            <Input placeholder='输入所在部门' />
                        </Form.Item>

                        <Form.Item
                            label="职位"
                            name="job"
                            rules={[{ required: true, message: '选择职位' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={staffManageJob}
                            />
                        </Form.Item>
                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '输入手机号' }]}
                        >
                            <Input placeholder='输入手机号' />
                        </Form.Item>
                        <Form.Item
                            label="员工状态"
                            name="leave"
                            rules={[{ required: true, message: '选择员工状态' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={staffLeaveList}
                            />
                        </Form.Item>
                        <Form.Item
                            label="添加时间"
                            name="time"
                            rules={[{ required: true, message: '输入添加时间' }]}
                        >
                            <Input placeholder='输入添加时间' />
                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
                            <Button type="primary" htmlType="submit" className="add">新增</Button>
                        </Form.Item>
                    </Form>
                    <div className="handleCancel">
                        <Button type="primary" htmlType="submit" onClick={handleCancel}>取消</Button>
                    </div>

                </Modal>
            </div>

            {/* 编辑的对话框 */}
            <div className="addStaff">
                <Modal title="编辑" open={isModalOpenEdit} footer={[]} className="editmodal"
                >
                    {/* footer={[]} 取消底部的两个按钮 */}
                    <Form
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        onFinish={onFinishEdit}
                        form={form}
                    >
                        <Form.Item
                            label="员工编号"
                            name="userid"
                            rules={[{ required: true, message: '输入员工编号' }]}
                        >
                            <Input placeholder='输入员工编号' />
                        </Form.Item>
                        <Form.Item
                            label="姓名"
                            name="name"
                            rules={[{ required: true, message: '输入姓名' }]}
                        >
                            <Input placeholder='输入姓名' />
                        </Form.Item>
                        <Form.Item
                            label="账号"
                            name="account"
                            rules={[{ required: true, message: '输入账号' }]}
                        >
                            <Input placeholder='输入账号' />
                        </Form.Item>
                        <Form.Item
                            label="所在部门"
                            name="department"
                            rules={[{ required: true, message: '输入所在部门' }]}
                        >
                            <Input placeholder='输入所在部门' />
                        </Form.Item>

                        <Form.Item
                            label="职位"
                            name="job"
                            rules={[{ required: true, message: '选择职位' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={staffManageJob}
                            />
                        </Form.Item>
                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '输入手机号' }]}
                        >
                            <Input placeholder='输入手机号' />
                        </Form.Item>
                        <Form.Item
                            label="员工状态"
                            name="leave"
                            rules={[{ required: true, message: '选择员工状态' }]}
                        >
                            <Select
                                style={{ width: 120 }}
                                options={staffLeaveList}
                            />
                        </Form.Item>
                        <Form.Item
                            label="添加时间"
                            name="time"
                            rules={[{ required: true, message: '输入添加时间' }]}
                        >
                            <Input placeholder='输入添加时间' />
                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 8, span: 16 }} >
                            <Button type="primary" htmlType="submit" className="editntn">保存修改</Button>

                        </Form.Item>
                    </Form>
                    <div className="edithandleCancel">
                        <Button type="primary" htmlType="submit" onClick={edithandleCancel}>取消</Button>
                    </div>

                </Modal>
            </div>

        </div>
    );
}
export default StaffManage;